import { Table, Input , TreeSelect, Row, Button ,DatePicker ,message, Modal,Select,Space,Menu } from 'antd';
const { Search } = Input;
import React, { useState, useEffect} from 'react';
import { EditableProTable } from '@ant-design/pro-table';
import { DownOutlined,PaperClipOutlined,SearchOutlined} from '@ant-design/icons';


import { queryAreaTree } from '@/services/area';
import { queryDeviceList } from '@/services/device';
import { unitReport ,queryDevicelistAndSet } from '@/services/energyAnalysis';
const { RangePicker } = DatePicker;
import styles from './style.less'
import moment from 'moment'
const { Option } = Select;

const Report: React.FC = () => {





  const cs = [
    {
      title: '本期',
      dataIndex: 'time',
      key: 'time',
    
    }, {
      title: '本期单位能耗',
      dataIndex: 'value',
      key: 'value',
    
    }
    , {
      title: '同比日期',
      dataIndex: 'ttime',
    }, {
      title: '同比单位能耗',
      dataIndex: 'tvalue',
    }, {
      title: '增减量',
      dataIndex: 'tdecrement',
    }, {
      title: '同比增长率',
      dataIndex: 'tGrowthRate',
    } , {
      title: '环比日期',
      dataIndex: 'htime',
    }, {
      title: '环比单位能耗',
      dataIndex: 'hvalue',
    }, {
      title: '增减量',
      dataIndex: 'hdecrement',
    }, {
      title: '环比增长率',
      dataIndex: 'hGrowthRate',
    }
  ];
const [selectData, setSelectData] = useState();
const [columns, setColumns] = useState(cs);
const [type, setType] = useState('month');
const [startdate, setStartdate] = useState(moment().startOf("year"));
const [enddate, setEndCdate] = useState(moment());

const [xwidth, setXwidth] = useState(1000);
const [areaTreeData, setAreaTreeData] = useState<API.TreeNodeItem[]>([]);
const [areaId, setAreaId] = useState('45');
const [areaName, setAreaName] = useState('变电站');
const [deviceName, setDeviceName] = useState('进线侧总表（副）');
const [deviceId, setDeviceId] = useState<number>(80000115);
const [deviceList, setDeviceList] = useState<API.DeviceItem[]>([]);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
  setAnalysisData(startdate,enddate,type,deviceId);
}, [])
  

useEffect(() => {
  setDevice();
   queryAreaTree().then((trees) => {
    setAreaTreeData(trees);
  });
   queryDeviceList({ areaId: areaId, deviceTypeId: 3 }).then((devices) => {
      setDeviceList(devices);
    });
    
}, [])


  const setDevice = async () => {
    let resultData = await queryDevicelistAndSet({ });
    let deviceList =resultData.list;
    let multiplier=resultData.multiplier||4000;
    let conversion=resultData.conversion||0.1229;
}

  const setAnalysisData = async (sdate,edate,ptype,deviceId) => {
    let date1=formatTime(sdate);
    let date2=formatTime(edate);
    const analysis = await unitReport({sdate:date1,edate:date2,type:ptype,deviceId});
       setSelectData(analysis);
       setLoading(false);
   }


    const ToExport = async () => {
      const hide = message.loading('导出中');
      try {
      console.log(areaName, deviceName,startdate,enddate)
     
        window.location.href="/api/energy/unitReport/export?type="+type+"&deviceId=" +deviceId+"&deviceName="+(areaName.replace("#","@")+"-"+deviceName.replace("#","@"))+"&sdate="+startdate.format('YYYY-MM')+"&edate="+enddate.format('YYYY-MM');
        return true;
      } catch (error) {
        hide();
        message.error('导出失败请重试！');
        return false;
      }
    };
    

    const  formatTime = (pdate) => {
      let date=moment(pdate).format("YYYY-MM-DD");
      if(type=="week"){
        date= moment(pdate).startOf('week').format('YYYY-MM-DD');
      }else if(type=="month"){
        date= moment(pdate).startOf('month').format('YYYY-MM');
      }else if(type=="quarter"){
        date= moment(pdate).startOf('quarter').format('YYYY-MM-DD');
      }
     
      return  date;
    }

   

  // 设备
  const OptionData = (list) => {
    if (!list || list.length < 1) {
      return (
        <Option key={''} value={''}>
          没有找到选项
        </Option>
      );
    }
    return list.map((item) => (
      <Option key={item.deviceId} value={item.deviceId}>
        {item.deviceName}
      </Option>
    ));
  };

   
  const changeDeviceList = async (e) => {
     setDeviceId(null);
    // setAnalysisData(deviceId, e, type);
     let devices = await queryDeviceList({areaId:e,deviceTypeId:3});
    // console.log(devices)
     setDeviceList(devices);
  };

  const changeDevice = async (e) => {
    setDeviceId(e);
    setAnalysisData(startdate,enddate,type,e);
    // setAnalysisData(e, areaId, type);
  };
  
  const changeType = async (e) => {
    setType(e);
    if(e=='date'){
      setStartdate(moment().startOf("month"));
    }else  if(e=='week'){
      setStartdate(moment().startOf("month"));
    }else  if(e=='month'||e=='quarter'){
      setStartdate(moment().startOf("year"));
    }else if(e=='year'){
      setStartdate(moment().subtract (1,"years").startOf("year"));
    }
  };
  

    return (
      <div  className={styles.main}>
        <Row className={styles.tabletop}>
          <Row style={{    alignItems: 'center'}}>
            <div className={styles.inputBg}>
              <TreeSelect
                onChange={(e,areaName) => {
                
                  setAreaName(areaName[0])
                  setAreaId(e);
                  changeDeviceList(e);
                }}
                style={{ width: '260px', marginLeft: '10px' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={areaTreeData}
                value={areaId}
                placeholder="请选择所在区域"
                treeDefaultExpandAll
              />
            </div>
            <div className={styles.inputBg}>
              <Select
                bordered={false}
                value={deviceId}
                onChange={(e,device) => {
                 
                  setDeviceName(device.children);
                  changeDevice(e);
                }}
                style={{ width: 'auto', minWidth: 120 }}
                placeholder="请选择设备"
                dropdownStyle={{ background: 'rgb(20, 49, 115)' }}
              >
                {OptionData(deviceList)}
              </Select>
            </div>
           {/* <div  className={styles.inputBg} >
              <Select value={type}  bordered={false}    dropdownStyle={{ background: 'rgb(20, 49, 115)'}}  onChange={(value)=>{changeType(value);}}>
                  <Option value="date">日</Option>
                  <Option value="week">周</Option> 
                  <Option value="month">月</Option>
                  <Option value="quarter">季度</Option> 
                  <Option value="year">年份</Option>
              </Select>
            </div>  */}
            <div  className={styles.inputBg} >
              <RangePicker picker={type} 
                onChange={(value)=>{
                  setAnalysisData(value[0],value[1],type);
                  setStartdate(value[0]);
                  setEndCdate(value[1]);
                }} 
                value={[startdate,enddate]}/>
            </div>(kw·h)
          </Row>
          <Button className={styles.exporttBtn}  onClick={()=>ToExport()}
            type="primary" >
              <PaperClipOutlined />
              导出
          </Button> 
        </Row>
        <Table 
          columns={columns}
          scroll={{ x: xwidth }} 
          loading={loading}
          rowKey="time"  dataSource={selectData}   pagination={{ position: ['none','none'] , pageSize: 31}} > 
        </Table>
 
    
  </div>
    );
};

export default Report;